const userModel = require('../models/userModel');
const JWT = require('../utils/JWT');
const md5 = require('../utils/md5');
const request = require('request');
const wxAppId = 'wx9b348b37f1bb591f';
const wxScret = 'cb785d1cf63ad8dac33d762242256e99';
const wxLogin = async(ctx, next) => {
	
	try{
		const token = await getOpenId(ctx);
		ctx.body = {
		    code: 1,
		    msg: '',
		    data: {
		        token
		    }
		};
	}catch(e){
		ctx.body = {
			code: -1,
			msg: e.message
		};
	}
}

const getOpenId = (ctx) => {
	const data = ctx.request.body;
	const code = data.code;
	const {avatarUrl, nickName, gender} = data;
	const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxAppId}&secret=${wxScret}&js_code=${code}&grant_type=authorization_code`;
	return new Promise((resolve, reject) => {
		request({
		    url,
		    method: 'GET',
		}, async function(error, res, body) {
		    let data = JSON.parse(body);
			const openId = data.openid;
			const user = await userModel.findOne({ openId });
			console.log(2);
			console.log(user);
			if (user) {
				// 如果用户登录过，更新用户信息
				await userModel.update({
					_id: user._id
				}, {
					avatarUrl,
					nickName,
					gender
				});
				console.log('已更新');
				resolve(JWT.generateToken(user._id, nickName));
			} else {
				// 创建新纪录
				const newData = {
					avatarUrl,
					nickName,
					gender,
					openId,
					status: 0, 
					createDate: new Date()
				}
				const result = await userModel.create(newData);
				console.log(1);
				resolve(JWT.generateToken(result._id, nickName));
				console.log('已经返回了token');
			}
		});
	});
}

// C端用户无需输入密码直接登录
const buyerLogin = async(ctx, next) => {
    const req = ctx.request.body;
    const { phone, password } = req;
    const user = await userModel.findOne({ phone });
    if (user) {
        ctx.body = {
            code: 1,
            msg: '',
            data: {
                token: JWT.generateToken(user.id, phone, user.username)
            }
        };
    } else if (password === 'C_A_123456') {
        // 自动创建新用户
        const result = await create(ctx, next);
        ctx.body = {
            code: 1,
            msg: '',
            data: {
                token: JWT.generateToken(result.id, phone, result.username)
            }
        };
    } else {
        ctx.body = {
            code: -1,
            msg: '用户名或密码错误',
            data: {}
        };
    }
}
const login = async(ctx, next) => {
    const req = ctx.request.body;
    const { phone, password } = req;
    const user = await userModel.findOne({ phone });
	console.log(md5.encode(phone + password));
    if (user && user.password === md5.encode(phone + password)) {
        ctx.body = {
            code: 1,
            msg: '',
            data: {
                token: JWT.generateToken(user.id, phone, user.username)
            }
        };
    } else {
        ctx.body = {
            code: -1,
            msg: '用户名或密码错误',
            data: {}
        };
    }
}
const create = async(ctx, next) => {
    const req = ctx.request.body;
    const data = Object.assign({ status: 0, createDate: new Date() }, req);
    const user = await userModel.findOne({ phone: req.phone });
    if (user) {
        ctx.body = {
            code: -1,
            msg: '用户已存在！',
            data: {}
        };
    } else {
        data.password = md5.encode(phone + data.password);
        const result = await userModel.create(data);
        if (result) {
            ctx.body = {
                code: 1,
                msg: '添加成功！',
                data: result
            };
        }
    }
}

const findById = async(ctx, next) => {
    const id = ctx.params.id;
    const result = await userModel.findById(id);
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const find = async(ctx, next) => {
    const query = ctx.request.query;
    const name = query.name;
    const condition = {
        status: {
            $gt: -1
        }
    };
    if (name) {
        condition.name = {
            $regex: name
        }
    }
    const result = await userModel.find(condition, null, {
        sort: {
            createDate: 'desc'
        }
    });
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const update = async(ctx, next) => {
    const req = ctx.request.body;
    const result = await userModel.update({
        _id: req._id
    }, req);
    if (result) {
        ctx.body = {
            code: 1,
            msg: '修改成功！',
            data: {}
        };
    }
}

module.exports = {
    create,
    find,
    update,
    findById,
    login,
    buyerLogin,
	wxLogin
};